package com.yonyou.cyxdms.sysAuth.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.basedata.client.domains.vo.DictVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.RegionVO;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonRegionService;
import com.yonyou.cyxdms.framework.constants.FrameworkDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.entity.TcMenuPremActionPO;
import com.yonyou.cyxdms.sysAuth.service.entity.TmPremActionPO;
import com.yonyou.cyxdms.sysAuth.service.feign.BaseDataService;
import com.yonyou.cyxdms.sysAuth.service.mapper.TcMenuPremActionMapper;
import com.yonyou.cyxdms.sysAuth.service.mapper.TmPremActionMapper;
import com.yonyou.cyxdms.sysAuth.service.service.DictService;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.MenuActionUrlDto;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author     ：quankk
 * @date       ：2019/7/9 15:46
 * @description：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DictServiceImpl implements DictService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(DictServiceImpl.class);

    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    public BaseCommonRegionService baseCommonRegionService;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    TcMenuPremActionMapper tcMenuPremActionMapper;

    @Autowired
    TmPremActionMapper tmPremActionMapper;

    /**
     * @author     ：quankk
     * @date       ：2019/7/9 18:04
     * @description：
     */
    //===========   CMS 删除缓存，解决区域查询混乱问题     开始    =======================
//    @Cacheable(value = Constanst.KEY_DICT, key = "'all'", unless = "#result==null")
    //===========   CMS 删除缓存，解决区域查询混乱问题     结束    =======================
    @Override
    public Map<String, Object> queryDicts() {
        logger.info("查询tc_code和省市开始。。。。。。。。。。。。。。");
        Map<String, Object> dict = new HashMap<>();

        // 定义缓存对象--身份
        Map<Long, RegionVO> regionCacheMap   = new HashMap<>();
        // 城市信息
        Map<Long, RegionVO> cityMap    = new HashMap<>();
        // 区县
        Map<Long, RegionVO> countryMap = new HashMap<>();
        // 街道
        Map<Long, RegionVO> streetMap  = new HashMap<>();

//        LambdaQueryWrapper<RegionPO> queryWrapper = new QueryWrapper().lambda();
//        queryWrapper.orderByAsc(RegionPO :: getRegionType).orderByAsc(RegionPO :: getRegionId);
//        List<RegionPO> regionPOList = regionMapper.selectList(queryWrapper);

//        LambdaQueryWrapper<RegionVO> queryWrapper = new QueryWrapper().lambda();
//        queryWrapper.orderByAsc(RegionVO :: getRegionType).orderByAsc(RegionVO :: getRegionId);
        List<RegionVO> regionpolist = baseCommonRegionService.listAllData();
        if (CollectionUtils.isNotEmpty(regionpolist)) {
            regionpolist.stream().forEach(regionpo -> {
                Integer type = regionpo.getRegionType();
                RegionVO regionDto = new RegionVO();
                regionDto.setRegionId(regionpo.getRegionId());
                regionDto.setRegionName(regionpo.getRegionName());
                regionDto.setRegionType(regionpo.getRegionType());
                Long parentId = !StringUtils.isNullOrEmpty(regionpo.getParentRegionId()) ? regionpo.getParentRegionId().longValue() : null;

                if (FrameworkDictCodeConstants.REGION_TYPE_PROVINCE == type) {
                    regionDto.setChildren(new HashMap<Long, RegionVO>());
                    regionCacheMap.put(regionDto.getRegionId(), regionDto);
                }

                if (FrameworkDictCodeConstants.REGION_TYPE_CITY == type) {
                    RegionVO parentDto = null;
                    parentDto = regionCacheMap.get(parentId);
                    regionDto.setChildren(new HashMap<Long, RegionVO>());
                    cityMap.put(regionDto.getRegionId(), regionDto);
                    parentDto.getChildren().put(regionDto.getRegionId(), regionDto);
                }

                if (FrameworkDictCodeConstants.REGION_TYPE_COUNTY == type) {
                    RegionVO parentDto = cityMap.get(parentId);
                    regionDto.setChildren(new HashMap<Long, RegionVO>());
                    countryMap.put(regionDto.getRegionId(), regionDto);
                    parentDto.getChildren().put(regionDto.getRegionId(), regionDto);
                }
                // 街道
                if (10001004 == type) {
                    RegionVO parentDto = countryMap.get(parentId);
                    parentDto.getChildren().put(regionDto.getRegionId(), regionDto);
                    streetMap.put(regionDto.getRegionId(), regionDto);
                }
            });
        }

        List<DictVO> dictList = baseDataService.allCodeAvailable().getData();
        Map<Integer,List<DictVO>> cacheMap = new HashMap<>();
        dictList.stream().forEach(dictVO->{
            Integer type = dictVO.getType();
            List<DictVO> listData = null;
            if(cacheMap.get(type)!=null){
                listData = cacheMap.get(type);
            }else{
                listData = new ArrayList<>();
                cacheMap.put(type, listData);
            }
            listData.add(dictVO);
        });

        dict.put("dict", cacheMap);
        dict.put("region", regionCacheMap);
        // add 20220809
        dict.put("menuActionUrls", queryMenuActionUrls());
        return dict;
    }

    @Override
    public List<MenuActionUrlDto> queryMenuActionUrls() {
        String appId = "RL";
        String redisActionUrlKey = MessageFormat.format(BaseDataCommonConstants.MENU_URL_ACTION_CACHE, appId);
        List<MenuActionUrlDto> list = new ArrayList<>();
        if(!redisClient.exists(redisActionUrlKey)){
            List<TcMenuPremActionPO> tcMenuPremActionPos = tcMenuPremActionMapper.selectList(
                    new LambdaQueryWrapper<TcMenuPremActionPO>().eq(TcMenuPremActionPO::getAppId, appId));
            for (TcMenuPremActionPO tcMenuPremActionPo : tcMenuPremActionPos) {
                MenuActionUrlDto dto = new MenuActionUrlDto();
                TmPremActionPO tmPremActionPo = tmPremActionMapper.selectById(tcMenuPremActionPo.getPremActionId());
                dto.setMenuId(tcMenuPremActionPo.getMenuId());
                dto.setPremActionId(tmPremActionPo.getId());
                dto.setModule(tmPremActionPo.getModule());
                dto.setActionUrl(tmPremActionPo.getActionUrl());
                dto.setActionMethod(tmPremActionPo.getActionMethod());
                list.add(dto);
            }
            redisClient.setList(redisActionUrlKey, list, BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
        }else{
            list = (List<MenuActionUrlDto>)redisClient.getListAll(redisActionUrlKey);
        }
        return list;
    }
}
